<template>
  <div class="stat-fields-config">
    <div v-if="statFields.length === 0" class="empty-state">
      <el-empty description="暂无统计字段配置" :image-size="80">
        <el-button type="primary" size="small" @click="addStatField">
          <el-icon><Plus /></el-icon>
          添加统计字段
        </el-button>
      </el-empty>
    </div>

    <div v-else>
      <div
        v-for="(statField, index) in statFields"
        :key="index"
        class="stat-field-item"
      >
        <el-card shadow="never" style="margin-bottom: 12px">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span>统计字段 {{ index + 1 }}</span>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                circle
                @click="removeStatField(index)"
              />
            </div>
          </template>

          <el-form :model="statField" label-width="120px">
            <el-form-item label="字段名" required>
              <el-select
                v-model="statField.field_name"
                placeholder="请选择或输入字段名"
                filterable
                allow-create
                default-first-option
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
                @change="handleStatFieldChange(index)"
              >
                <el-option
                  v-for="field in availableFields"
                  :key="field"
                  :label="field"
                  :value="field"
                />
              </el-select>
              <div style="margin-top: 8px; font-size: 12px; color: #909399;">
                目标表中的字段名，如：is_on_sales
              </div>
            </el-form-item>

            <el-form-item label="统计类型" required>
              <el-select
                v-model="statField.type"
                placeholder="请选择统计类型"
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
                @change="handleStatFieldChange(index)"
              >
                <el-option label="求和 (SUM)" value="sum" />
                <el-option label="计数 (COUNT)" value="count" />
              </el-select>
            </el-form-item>

            <!-- 如果模板定义了字段映射规则，显示所有条件和输出字段 -->
            <template v-if="getFieldMapping(statField.field_name)">
              <el-form-item label="条件与输出字段">
                <div
                  v-for="(outputField, idx) in getFieldMapping(statField.field_name)?.output_fields || []"
                  :key="idx"
                  style="margin-bottom: 12px; padding: 12px; background: #f5f7fa; border-radius: 4px;"
                >
                  <div style="display: flex; align-items: center; margin-bottom: 8px;">
                    <el-tag type="primary" style="margin-right: 8px;">
                      条件 {{ idx + 1 }}
                    </el-tag>
                    <span style="font-weight: 500; color: #606266;">
                      {{ statField.field_name }} {{ getFieldMapping(statField.field_name)?.conditions?.[idx] || '无' }}
                    </span>
                  </div>
                  <div style="display: flex; align-items: center;">
                    <el-icon style="color: #67c23a; margin-right: 4px;"><InfoFilled /></el-icon>
                    <span style="color: #67c23a; font-size: 12px;">输出字段：</span>
                    <el-tag type="success" style="margin-left: 4px;">
                      {{ outputField }}
                    </el-tag>
                  </div>
                </div>
                <div style="margin-top: 12px; padding: 12px; background: #ecf5ff; border-left: 4px solid #409eff; border-radius: 4px;">
                  <div style="font-size: 12px; color: #409eff; margin-bottom: 4px;">
                    <el-icon><InfoFilled /></el-icon>
                    <strong>说明：</strong>模板映射规则支持多种条件格式，不仅限于 0 和 1
                  </div>
                  <div style="font-size: 12px; color: #606266; margin-left: 20px;">
                    • 等值条件：<code>=0</code>, <code>=1</code>, <code>='value'</code><br />
                    • 比较条件：<code>&gt;100</code>, <code>&lt;50</code>, <code>&gt;=10</code>, <code>&lt;=20</code><br />
                    • 不等条件：<code>!=0</code>, <code>&lt;&gt;1</code><br />
                    • 范围条件：<code>BETWEEN 10 AND 20</code>（需在模板中定义）
                  </div>
                </div>
                <div style="margin-top: 8px; font-size: 12px; color: #67c23a;">
                  <el-icon><InfoFilled /></el-icon>
                  此字段将根据模板定义自动生成上述所有输出字段
                </div>
              </el-form-item>
            </template>

            <!-- 如果没有映射规则，显示单个条件输入 -->
            <template v-else>
              <el-form-item label="条件">
                <el-input
                  v-model="statField.condition"
                  placeholder="如：=0, =1, >100, >=10, !=0"
                  style="width: 100%"
                  @change="handleStatFieldChange(index)"
                />
                <div style="margin-top: 8px; font-size: 12px; color: #909399;">
                  可选，统计条件，支持多种格式：
                </div>
                <div style="margin-top: 4px; margin-left: 12px; font-size: 12px; color: #909399;">
                  • 等值：<code>=0</code>, <code>=1</code>, <code>='value'</code><br />
                  • 比较：<code>&gt;100</code>, <code>&lt;50</code>, <code>&gt;=10</code>, <code>&lt;=20</code><br />
                  • 不等：<code>!=0</code>, <code>&lt;&gt;1</code>
                </div>
              </el-form-item>

              <el-form-item label="输出字段名" required>
                <el-input
                  v-model="statField.output_field"
                  placeholder="如：dws_is_on_sales_count 或 在售商品数（必填）"
                  style="width: 100%"
                  @change="handleStatFieldChange(index)"
                />
                <div style="margin-top: 8px; font-size: 12px; color: #909399;">
                  必填，作为 SQL 列名和报表显示列名。建议使用英文（如：dws_is_on_sales_count），也可使用中文（如：在售商品数）
                </div>
              </el-form-item>
            </template>
          </el-form>
        </el-card>
      </div>

      <el-button
        type="primary"
        :icon="Plus"
        @click="addStatField"
        style="width: 100%; margin-top: 12px"
      >
        添加统计字段
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { Plus, Delete, InfoFilled } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: [Object, String, Array],
    default: () => ({})
  },
  availableFields: {
    type: Array,
    default: () => []
  },
  fieldMappings: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const statFields = ref([])
const isInternalUpdate = ref(false)

const getFieldMapping = (fieldName) => {
  return props.fieldMappings[fieldName] || null
}

const addStatField = () => {
  statFields.value.push({
    field_name: '',
    type: 'sum',
    condition: '',
    output_field: ''
  })
}

const removeStatField = (index) => {
  statFields.value.splice(index, 1)
  emitChange()
}

const handleStatFieldChange = () => {
  emitChange()
}

const emitChange = () => {
  const statFieldsConfig = {}
  statFields.value.forEach((field) => {
    // 只有当字段名和输出字段名都存在时才保存配置
    if (field.field_name && field.output_field) {
      const config = {
        type: field.type || 'sum'
      }
      if (field.condition) {
        config.condition = field.condition
      }
      // 输出字段名现在是必填的
      config.output_fields = [field.output_field]
      statFieldsConfig[field.field_name] = config
    }
  })

  const value = Object.keys(statFieldsConfig).length > 0 ? statFieldsConfig : {}

  isInternalUpdate.value = true
  emit('update:modelValue', value)
  emit('change', value)
  nextTick(() => {
    isInternalUpdate.value = false
  })
}

watch(
  () => props.modelValue,
  (newValRaw) => {
    if (isInternalUpdate.value) return

    let newVal = newValRaw
    try {
      if (typeof newVal === 'string' && newVal.trim()) {
        try {
          newVal = JSON.parse(newVal)
        } catch (e) {
          console.warn('解析统计字段配置失败:', e)
          statFields.value = []
          return
        }
      }

      if (newVal && typeof newVal === 'object') {
        if (Array.isArray(newVal)) {
          statFields.value = newVal.map((field) => ({
            field_name: field.field_name || '',
            type: field.type || 'sum',
            condition: field.condition || '',
            output_field: field.output_field || ''
          }))
        } else {
          const entries = Object.entries(newVal)
          if (entries.length === 0 && statFields.value.length > 0) {
            return
          }
          statFields.value = entries.map(([fieldName, config]) => ({
            field_name: fieldName,
            type: (config && config.type) || 'sum',
            condition: (config && config.condition) || '',
            output_field:
              (config && config.output_field) ||
              (config && config.output_fields && config.output_fields[0]) ||
              ''
          }))
        }
      } else {
        if (statFields.value.length > 0) {
          return
        }
        statFields.value = []
      }
    } catch (e) {
      console.error('处理统计字段配置失败:', e)
      if (statFields.value.length === 0) {
        statFields.value = []
      }
    }
  },
  { immediate: true, deep: true }
)
</script>

<style scoped>
.stat-fields-config {
  width: 100%;
}

.empty-state {
  padding: 20px;
  text-align: center;
}

.stat-field-item {
  margin-bottom: 12px;
}
</style>


